<?php
namespace Helper;

class Logger {
    protected $_logFile;
    static $LOG_FILE='';
    
    public function __construct($file=null)
    {
        $this->_logFile = $file;
    }
    
    static public function record($logText, $print=true) {
        $logText = $logText . "\n";
        
        if($print) {
            echo $logText;
        }
        
        $logfile = self::_getLogFile();
        $time = self::_timestr();
        
        file_put_contents($logfile, "[$time] $logText", FILE_APPEND);
    }
    
    static protected function _getLogFile() {
        $logfile = self::$LOG_FILE;
    
        if(!$logfile) {
            $filename = basename($_SERVER['argv'][0]) . '.log';
            $logfile = dirname(__DIR__) . "/log/$filename";
        } else {
            $logfile = dirname(__DIR__)  . "/log/{$logfile}";
        }
    
        $logdir = dirname($logfile);
    
        if(!file_exists($logdir)) {
            mkdir($logdir, true);
            chmod($logdir, 0777);
        }
        
        return $logfile;
    }
    
    static protected function _timestr() {
        list($sec, $usec) = explode('.', strval(microtime(true)), 2);
        return date('Y-m-d H:i:s', $sec) . '.' . str_pad($usec, 4, '0', STR_PAD_RIGHT);
    }
    
    static public function recordForwardContent($title, $content) {
        $logfile = self::_getLogFile();
        $logfile = dirname($logfile) . '/fwc.' . basename($logfile);
        $time = self::_timestr();
        $content = base64_encode($content);
        file_put_contents($logfile, "[$time] ====== $title ======\n$content\n===============================\n\n", FILE_APPEND);
    }
}